package com.golden.order02.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.golden.order02.service.OrderDocumentService;
import com.golden.order02.service.OrderGroupService;




public class OrderNewFactory {
	
	private static AtomicBoolean isInit = new AtomicBoolean(false);
	
	private static ApplicationContext context = null;
	
	private static AtomicBoolean isTest = new AtomicBoolean(false);
	
	public static void initCofing() {
		Properties properties = new Properties();
		InputStream in = OrderNewFactory.class.getClassLoader().getResourceAsStream("application.properties");
		try {
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String value = properties.getProperty("run.test");
		if(value.equals("on")) {
			isTest.set(true);
		}
		if (!isInit.get()) {
			if(isTest.get()) {
				context = new FileSystemXmlApplicationContext(
						"classpath:orderNew-test-application.xml");
				System.out.println("init test application.xml");
			} else {
				context = new FileSystemXmlApplicationContext(
						"classpath:orderNew-application.xml");
				System.out.println("init application.xml");
			}
			isInit.set(true);
		}	
	}
	
	public static OrderGroupService getOrderGroupService() {
		initCofing();
		OrderGroupService orderGroupService = (OrderGroupService) context.getBean("orderGroupService");
		return orderGroupService;
	}
	
	public static OrderDocumentService getOrderDocumentService() {
		initCofing();
		OrderDocumentService orderDocumentService = (OrderDocumentService) context.getBean("orderDocumentService");
		return orderDocumentService;
	}
	
	
}
